<template>
	<div class="layer-manager">
		<!--标题-->
		<div class="title">组件图层</div>
		<!--内容-->
		<div class="content">
			<div id="cpnt-tree-container" class="cpnt-tree-container">
				<el-tree
					v-if="store.isTree && cpntNavTree.length"
					ref="cpntTree"
					v-loading="state.cpntTreeLoading"
					class="cpnt-tree"
					:highlight-current="true"
					:check-strictly="true"
					:data="cpntNavTree"
					:default-checked-keys="[cpntNavTree[0].uuid]"
					:props="state.cpntProps"
					node-key="uuid"
					:draggable="true"
					:allow-drop="allowDrop"
					@node-drop="handleDrop"
					@node-click="handleNodeClick">
					<!-- :render-content="renderContent" -->
					<template #default="{ node, data }">
						<el-tooltip
							popper-class="layer-manager-tips"
							effect="dark"
							placement="right"
							:open-delay="1200">
							<div class="custom-tree-node" :id="node.id">
								<div class="logo-wrapper">
									<img class="icon" :src="data.getIcon()" />
								</div>
								<div class="detail">
									<div class="header-container">
										<div class="header">
											<span class="name">{{ node.label }}</span>
										</div>
									</div>
									<div class="introduction">
										{{ data.getCpntLibEntryRef()?.introduction || '暂无简介' }}
									</div>
									<div class="footer">
										<div
											class="cpnt-type"
											:aria-label="getNodeTypeInfo(data.nodeType)[1]"
											:title="getNodeTypeInfo(data.nodeType)[1]">
											{{ getNodeTypeInfo(data.nodeType)[0] }}
										</div>
										<div class="action-bar">
											<el-icon @click="triggerCanvasScrollToCpnt(data)"><Position /></el-icon>
											<el-icon @click.stop="handleNodeDelete(data, $event)"><Delete /></el-icon>
											<!-- <el-icon @click="showCpntDetails"><Document /></el-icon> -->
										</div>
									</div>
								</div>
							</div>
							<template #content>
								<div class="cpnt-tips">
									<div class="header">
										<span class="name">{{ node.label }}</span>
										<span class="version">v{{ data.getCpntDefRef()?.version }}</span>
									</div>
									<div class="divider"></div>
									<div class="introduction">
										{{ data.getCpntLibEntryRef()?.introduction || '暂无简介' }}
									</div>
									<div class="divider"></div>
									<div class="discription">
										{{ data.getCpntLibEntryRef()?.discription || '暂无详情' }}
									</div>
									<div class="divider"></div>
									<div class="record">
										<span class="author">{{ data.getCpntLibEntryRef()?.author || '无名氏' }}</span>
										<span class="update-time">{{ data.getCpntLibEntryRef()?.updateDate }}</span>
									</div>
								</div>
							</template>
						</el-tooltip>
					</template>
				</el-tree>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, toRefs, computed, watch } from 'vue';
import StorageHelper from '@CIF/Runtime/Global/storage';
import {
	ComponentTreeHelper,
	ComponentTreeNodeTypeEnum
} from '@CIF/ComponentTemplate/componentTree';
import { RUNTIME_CFG_ENUM } from '@CIF/Runtime/Global/variable';
import { usePrimaryStore } from '@/store';
import Notifier from '@CIF/Utils/Notifier.js';
import { ElMessage } from 'element-plus';
import { getUniqueVersionName } from '@CIF/ComponentLoader/dynamicComponentLoader.js';

const store = usePrimaryStore();
const state = reactive({
	cpntTreeLoading: false,
	cpntProps: {
		label: 'name',
		children: 'children'
	}
});
const cpntNavTree = computed(() => {
	return store.getCpntTree;
});
// watch(
// 	() => cpntNavTree.value,
// 	(newTree) => {
// 		console.log('3333-------------------------------newTree', newTree);
// 		// 为了触发重新渲染，若有更好的方法可替换
// 		// store.isTree = false;
// 		// setTimeout(() => {
// 		// 	store.isTree = true;
// 		// }, 0);
// 	},
// 	{ deep: true }
// );
/**
 * 拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
 * @param {*} draggingNode
 * @param {*} dropNode
 * @param {*} type
 */
function allowDrop(draggingNode, dropNode, type) {
	if (dropNode.data.nodeType === ComponentTreeNodeTypeEnum.NORMAL) {
		return type !== 'inner';
	} else {
		return true;
	}
}
/**
 * 拖拽成功完成时触发的事件
 * 共四个参数，依次为：被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置（before、after、inner）、event
 * @param {*} draggingNode
 * @param {*} dropNode
 * @param {*} dropType
 * @param {*} ev
 */
function handleDrop(draggingNode: any, dropNode: any, dropType: any, ev: any) {
	console.log('treetree drop: ', draggingNode, dropNode, dropType, ev);

	const appCpntTree = StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_COMPONENT_TREE);
	ComponentTreeHelper.getTreeFlatLayer(appCpntTree); // 刷新组件树排序
}
function handleNodeClick(cpntTreeNode: any) {
	// 文件夹类型的节点不需要展示配置面板
	const treeNodeInfo = {
		id: cpntTreeNode.uuid,
		type: cpntTreeNode.nodeType
	};
	store.setSelectedCpntTreeNodeInfo([treeNodeInfo]);
}
function getNodeTypeInfo(cpntTreeNodeType: any) {
	switch (cpntTreeNodeType) {
		case ComponentTreeNodeTypeEnum.NORMAL:
			return ['普通', '普通类型组件'];
		case ComponentTreeNodeTypeEnum.CONTAINER:
			return ['容器', '容器类型组件，选中可添加子组件'];
		case ComponentTreeNodeTypeEnum.FOLDER:
		default:
			return ['文件夹', '文件夹，选中可添加子组件'];
	}
}
function showCpntDetails() {
	ElMessage('功能尚在研发中, 或将于CIF v1.1.0版本提供');
}
// 移除节点
function handleNodeDelete(cpntTreeNode: any, event: any) {
	event.stopPropagation(); // 阻止点击事件冒泡
	if (cpntTreeNode.__local === true) {
		ElMessage.info('本地组件无法移除');
		return;
	}
	const cpntTreeData = StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_COMPONENT_TREE);
	const loader = StorageHelper.get(RUNTIME_CFG_ENUM.DYNAMIC_COPONENT_LOADER);
	const def = cpntTreeNode.getCpntDefRef();
	loader.dispose(getUniqueVersionName(def), def.id, cpntTreeData, def.name);
	ComponentTreeHelper.deleteTreeNodeToTree(cpntTreeData, cpntTreeNode.uuid);
}
// 定位组件
function triggerCanvasScrollToCpnt(cpntTreeNode: any) {
	console.log('triggerCanvasScrollToCpnt', cpntTreeNode);
	Notifier.broadcastInChannel('LAYER_MANAGER_TRIGGER_CPNT_LOCATION', cpntTreeNode);
}

onMounted(() => {});
defineExpose({ ...toRefs(state) });
</script>

<style lang="scss" scoped>
$layerMgrFontSize: 14px;
$layerMgrTitleHeight: 28px;
$discriptionForeground: rgba(248, 248, 242, 0.7);
.layer-manager {
	height: 100%;
	width: 100%;
	max-width: 300px;
	font-size: $layerMgrFontSize;
	box-sizing: border-box;
	color: var(--white);
	background-color: var(--dropdown-background);
	z-index: 1;
	border-top: solid 2px #000000;
	border-bottom: solid 2px #000000;
	.title {
		height: $layerMgrTitleHeight;
		line-height: 26px;
		padding: 0 8px;
		box-sizing: border-box;
		/* background-color: rgb(25 25 27); */
		background-color: var(--primary-plain);
		border-bottom: solid 2px #000000;
	}
	.content {
		height: calc(100% - $layerMgrTitleHeight);
		position: relative;
		.cpnt-tree-container {
			height: 100%;
			position: relative;
			/* overflow-x: hidden; */
			overflow-y: scroll;

			.cpnt-tree {
				min-height: 100%;
				background-color: transparent;
				color: var(--white);
				&.el-tree--highlight-current {
					.el-tree-node.is-current > .el-tree-node__content {
						background-color: var(--primary-active);
						box-shadow: #000000 0px 0px 6px 0px;
					}
				}
				:deep(.el-tree-node:focus > .el-tree-node__content) {
					background-color: var(--primary-high);
				}
				:deep(.el-tree-node.is-current > .el-tree-node__content) {
					background-color: var(--primary-high);
				}
				:deep(.el-tree-node__content) {
					height: 62px;
					box-sizing: border-box;
					border-bottom: solid 1px #080808;

					&:hover {
						/* background-color: rgba(68, 71, 90, 0.46); */
						background-color: var(--primary-hover);
						box-shadow: #000000 0px 0px 6px 0px;
					}

					.custom-tree-node {
						box-sizing: border-box;
						width: 100%;
						height: 100%;
						padding: 0;
						overflow: hidden;
						display: flex;
						cursor: pointer;

						.logo-wrapper {
							position: relative;

							.icon {
								width: 42px;
								height: 42px;
								margin: 10px 14px 10px 0;
								flex-shrink: 0;
								object-fit: contain;
								background-color: var(--dropdown-background);
							}
						}

						.detail {
							flex: 1;
							padding: 4px 0;
							overflow: hidden;

							.header-container {
								height: 18px;
								line-height: 18px;
								display: flex;
								overflow: hidden;
								padding-right: 11px;

								.header {
									display: flex;
									align-items: center;
									flex-wrap: nowrap;
									overflow: hidden;
									flex: 1;
									min-width: 0;

									.name {
										font-weight: 700;
										flex: 1;
										white-space: nowrap;
										text-overflow: ellipsis;
										overflow: hidden;
									}
								}
							}

							.introduction {
								padding-right: 11px;
								color: $discriptionForeground;
								overflow: hidden;
								white-space: nowrap;
								text-overflow: ellipsis;
								height: 18px;
								line-height: 18px;
							}

							.footer {
								display: flex;
								justify-content: flex-end;
								padding-right: 7px;
								height: 18px;
								line-height: 18px;
								overflow: hidden;

								.cpnt-type {
									color: #e2e2dd;
									flex: 1;
									display: flex;
									align-items: center;
									overflow: hidden;
									white-space: nowrap;
									text-overflow: ellipsis;
								}

								.action-bar {
									margin-right: 2px;
									white-space: nowrap;
									height: 100%;

									i {
										margin: 0 2px;
										font-size: 16px;
										margin-top: 2px;

										&:hover {
											background-color: rgba(90, 93, 94, 0.61);
											/* box-shadow: #000000 3px 3px 6px 1px; */
										}
									}

									.disable {
										cursor: not-allowed;
									}
								}
							}
						}
					}
				}
			}
		}
	}
}
.layer-manager-tips {
	&.el-tooltip__popper.is-dark {
		background: var(--dropdown-background) !important;
		color: var(--white) !important;
	}

	.cpnt-tips {
		width: 448px;
		line-height: 22px;
		font-size: 14px;

		.header {
			font-weight: 700;

			.name {
			}
			.version {
				margin-left: 8px;
				font-style: italic;
				background-color: var(--primary-active) !important;
			}
		}
		.introduction {
		}
		.discription {
		}
		.record {
			display: flex;
			.author {
				flex: 1;
			}
			.update-time {
			}
		}
		.divider {
			width: 100%;
			margin: 2px 0;
			height: 1px;
			background: rgba(255, 255, 255, 0.3) !important;
		}
	}
}
</style>
